import U from './conf';
import axios from 'axios'
//import qs from 'qs'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// POST传参序列化
/**axios.interceptors.request.use((config) => {
    if (config.method === 'post') {
        config.data = qs.stringify(config.data)
    }
    return config
}, (error) => {
    return Promise.reject(error)
}) */
//axios.get(U.getip)访问记录
export default {
    Index:{/*首页相关数据*/
        mainData:null,
        cache:null,
        listData:null,
        serData:null,
        async main(){
            return Promise.resolve(this.mainData = this.mainData || await axios.get(U.ban))
            /*if(this.mainData){
                
            }else{
                this.mainData = await axios.get(U.ban)
                return Promise.resolve(this.mainData)
            }*/
        },
        async serverTime(){
            return Promise.resolve(this.serData = this.serData || await axios.get(U.serinfo))
            /*if(this.serData){
                
            }else{
                this.serData = await axios.get(U.serinfo)
                return Promise.resolve(this.serData)
            }*/
        },
        async more(indextype){
            return await axios.get(U.indmorelist,{params :{indextype}})
        },
        async noticeDet(id){
            return await axios.get(U.noticedet,{params :{id}})
        },
        async noticeList(page){
            return await axios.get(U.notice,{params:{page}})
        },
        async list(page){
            return await axios.get(U.typelist,{params :{page}})
        },
        async listMore(page){
            return await axios.get(U.loadlist,{params :{page,type:0}})
        }
    },
    /*Game:{
        async main(){
            return await axios.get(U.gamelist)
        },
        async search(gameid,ordertype){
            return await axios.get(U.gamelist,{params :{gameid,ordertype}})
        },
        async select(){
            return await axios.get(U.gameselect)
        },
        async detail(goods_id){
            return await axios.get(U.gamedet,{params :{goods_id}})
        }
    },*/
    Classify:{
        cache:null,
        async main(type,init){
            return Promise.resolve(this.cache = (this.cache && init) ? this.cache : await axios.get(U.cate,{params :{type}}))
        },
        async getMore(page,type){
            return await axios.get(U.cate,{params :{page,type}})
        }
    },
    Search:{
        async main(type,searchname){
            const urls=type==0?U.search:U.giftsea;
            return await axios.get(urls,{params :{searchname}})
        }
    },
    Detail:{
        async main(gameid){
            return await axios.get(U.info,{params :{gameid}})
            /*return await Promise.all([
                axios.get(U.info,{params :{gameid}}),
                axios.get(U.comment,{params :{gameid}}),
                axios.get(U.gift,{params :{gameid}})
                //axios.get(U.infolist,{params :{gameid}}),
            ])*/
        },
        async download(gameid){
            return await axios.get(U.down,{params :{gameid}})
        },
        downloadCount(gameid,appid){///api/stat/downstatistics
            axios.post(U.count,{gameid,appid})
        }
    },
    Gift:{
        cache:null,
        async main(){
            return Promise.resolve(this.cache = this.cache || await axios.get(U.indgift))
            /*if(this.cache){
                
            }else{
                this.cache = await axios.get(U.indgift)
                return Promise.resolve(this.cache)
            }*/
        },
        async more(datakey){
            return await axios.get(U.moregift,{params :{datakey}})
        },
        async detail(infoid){
            return await axios.get(U.infogift,{params :{infoid}})
        }
    },
    Sign:{
        async sendForm(arg){
            return await axios.post(U.reg,arg)
        },
        async captcha(mobile){
            return await axios.post(U.code,mobile)
        },
        async check(reg){
            return await axios.get(U.signcheck,{params :{reg}})
        }
    },
    Voucher:{
        async main(){
            return await Promise.all([
                axios.get(U.vouevent),
                axios.get(U.vouindex)
            ])
        }
    },
    Download:{
        async main(c){
            return await axios.get(U.qrcode,{params :{c}})
        }
    },
    Rank:{
        cache:null,
        async main(){
            return Promise.resolve(this.cache = this.cache || await axios.get(U.rank))
            /*if(this.cache){
                
            }else{
                this.cache = await axios.get(U.rank)
                return Promise.resolve(this.cache);
            }*/
            
        }
    }
}
/**另一种实现更简结些 带加密，如果不需要可以去掉
 *  VUE_APP_sPath表示接口域名 
 * 使用示例：
 * const Fetch=new API();
 * Fetch.home({a:11,b:22}).then(data=>{ doSomething... }).catch(error=>{ //处理异常 })
 * */
const conf=[//如果导出在前面要加上export
    { fnName: 'home',          url: '/index/newindex',                        type: 'get' },//首页
    { fnName: 'captcha',       url: '/auth/sendmobilecode',    isEncry:true,  type: 'post'},//获取手机验证码（备注：isEncry可以省略或者设置为false表示不加密）
    { fnName: 'uploadimg',     url: '/auth/upload',                           type: 'upload'},//上传图片
]
class Base64 {//如果导出在前面要加上export default 
  constructor(){
    // private property 
    this.arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
      'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
      'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
      'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
      'Z', '*', '!', '/', '+', '=', '#'];
    this.arrlen = this.arr.length;
     
    this._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  }
  
  decode(words) {
    var first = words[0],
        len = words.length,
        end = words[len - 1],
        strnum = '',
        endstr = '',
        output = null;
    if (first === 'x' && end === 'y') {
      var tem = words.slice(1, len - 1),
          temlist = tem.split('_');
      temlist.forEach((el, i) => {
        strnum = parseInt(el) - this.arr[i % this.arrlen].charCodeAt();
        endstr += String.fromCharCode(strnum)
      })
      
      output = JSON.parse(this.decompression(endstr))
    }
    return output;
  }
  /**
   * 编码逻辑顺序
   *  ·将传入参数通过json.stringify转成字符串
   *  ·用base64进行转译再分割生成数组
   *  ·遍历上一步的数组混淆生成对应的ascii码
   *  ·用join连接数组并加上头尾的字符串
   */
  encode(words) {
    var strs = JSON.stringify(words),
      temlist = this.compression(strs).split(''),
        strnum = [],
        endstr = '';
    temlist.forEach((el, i) => {
      strnum.push(el.charCodeAt() + this.arr[i % this.arrlen].charCodeAt())
    })
    endstr = `x${strnum.join('_')}y`;
    
    return endstr;
  }
  // public method for encoding  
  compression(input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = this._utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
    }
    return output;
  }

  // public method for decoding  
  decompression(input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = this._utf8_decode(output);
    return output;
  }

  // private method for UTF-8 encoding  
  _utf8_encode(string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }
    return utftext;
  }

  // private method for UTF-8 decoding  
  _utf8_decode (utftext) {
    var string = "";
    var i = 0,
        c =0,
        c1 = 0,
        c2 = 0,
        c3 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}

export default class API extends Base64{//封装请求方法，此方法可以不加载qs模块
    constructor(){
        super();
        conf.forEach(({ fnName, url, type, isEncry }) => {
            this[fnName] = (data) => {
                return this[type](url, data,isEncry)
            }
        })
    }
    async get(url,params=''){
        try {
            const {data:{data,sendmsg,sendstatus}} = await axios.get(`${VUE_APP_sPath}${url}${params}`);
            if(sendstatus === '400' || sendstatus === '500'){
                return Promise.reject(sendmsg);
            }
            return Promise.resolve(data);
        } catch (error) {
            console.log(error)
        }
        
    }
    async post(url,json='',isEncry=false){
        let form =new FormData(),
            user = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : null,
            params = user ? Object.assign(user,json) : json;
        if(params!=''){
            console.log('未加密传参：',params);
            if(isEncry){//加密传递参数
                form.append('data',this.encode(params));
            }else{
                for(var i in params){
                    form.append(i,params[i])
                }
            }
        }else{
            form=''
        }
        try {
            const { data:{data:enData} } = await axios.post(`${VUE_APP_sPath}${url}`,form),
                body = isEncry ? this.decode(enData) : enData;//解密后台数据;
            //console.log('解密参数：',body);
            if(body.sendstatus === '400'){
                //localStorage.removeItem('userInfo');
                //location.href="/sign?type=0";
                //return;
                console.log(body.sendmsg)
                return;
            }  
            if(body.sendstatus === '500'){
                return Promise.reject(body.sendmsg);
            }
            return Promise.resolve(body.data);
        } catch (error) {
            console.log(error)
        }
    }
    async upload(url,file){//图片上传
        const form = new FormData(),
                config = {
                    headers: {'Content-Type': 'multipart/form-data'}
                },
                user = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : null;
            if(user) form.append('data',this.encode(user));
            form.append('images',file);
        try {
            const { data:{data:enData} } = await axios.post(`${VUE_APP_sPath}${url}`,form,config),
                body = this.decode(enData);
            if(body.sendstatus === '400' || body.sendstatus === '500'){
                return Promise.reject(body.sendmsg);
            }
            return Promise.resolve(body.data);
        } catch (error) {
            console.log(error)
        }
    }
}